package com.apestech.framework.sql.lib;

import java.util.ArrayList;

import com.apestech.framework.json.JSONObject;
import com.apestech.framework.sql.MultiDataBase;
import com.apestech.framework.util.StringFuncUtil;

public class ProcSql extends StringFuncUtil {
	
	private String sql;
	private String operSql;
	private String tabname;
	private int fieldStart=-1;
	private int fieldEnd=-1;
	
	public ProcSql(String sql) throws Exception{
		this.sql=sql;
		this.operSql=sql.toLowerCase();
		String error=check();
		if(!"".equals(error)){
			throw new Exception(error);
		}
		getTabname();
		getSqlstructure();
	}
	
	/**
	 * 返回空串代表无错，有错返回错误信息，不会判断全表操作
	 * @return
	 */
	public String check(){
		try {
			checkUpdate();
		} catch (Exception e) {
			return e.getMessage();
		} 
		return "";
	}
	
	/**
	 * 更新SQL有效性检查
	 * @param alldata
	 * @throws Exception
	 */
	private void checkUpdate() throws Exception{
		int count=this.countString(" "+this.operSql, " call ");
		if(count>1){
			throw new Exception(getMessage("SqlPaste_errorProcSql","call关键字只能有一个，实际有[({0})]个!",count));
		}
		if(this.operSql.indexOf(" call ")<0){
			throw new Exception(getMessage("SqlPaste_errorProcSqlKey","请输入正确的更新SQL:缺少关键字[({0})]!","call"));
		}
	}
	
	/**
	 * 获取操作表名
	 */
	private void getTabname(){
		int start=this.operSql.indexOf("call ")+5;
		int end=this.operSql.indexOf(" ( ");
		this.tabname=this.sql.substring(start, end).trim();
	}
	
	/**
	 * 获取表名
	 * @return
	 */
	public String getTableName(){
		return this.tabname;
	}
	
	/**
	 * 获取SQL相关结构位置信息
	 * @throws Exception 
	 */
	private void getSqlstructure() throws Exception{
		int count=this.countString(this.operSql," where ");
		if(count==0){
			this.fieldEnd=this.operSql.length();
		} else if(count>0){
			ArrayList<String> list=getBracket(this.operSql);
			int len=list.size();
			int pos=0;
			for(int i=0; i<len; i++){
				String sub=list.get(i);
				if(sub.indexOf("(")<0 && sub.indexOf(")")<0 && sub.indexOf(" where ")>=0){
					pos=pos+sub.indexOf(" where ");
					break;
				} else {
					pos=pos+sub.length();
				}
			}
			this.fieldEnd=pos;
		}
		this.fieldStart=this.operSql.indexOf(" set ")+5;
	}
	
	/**
	 * 获取主更新语句中的更新字段子串
	 * @return
	 * @throws Exception
	 */
	public String getUpdateField() throws Exception{
		return this.sql.substring(this.fieldStart,this.fieldEnd);
	}
	
	/**
	 * 获取主更新语句中的WHERE条件子串
	 * @return
	 * @throws Exception
	 */
	public String getUpdateWhere() throws Exception{
		return this.sql.substring(this.fieldEnd, this.sql.length());
	}
	
	/**
	 * 获取更新SQL结构
	 * @return
	 * @throws Exception
	 */
	public JSONObject getSqlStructure() throws Exception{
		JSONObject map=new JSONObject();
		map.put("field", getUpdateField());
		map.put("where", getUpdateWhere());
		return map;
	}
	
}
